package ru.pstu.itas.cps;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {

	CPSClientConnection netClient = null;
	TextView log = null;
	SimulatorView myview = null;
	volatile String selectedPanel = null; 

	private void setConnectionView() {
		setContentView(R.layout.connection);
		TextView caption = (TextView) findViewById(R.id.textView_Caption);
		String captionText = getText(R.string.app_name) + " " + getText(R.string.version);
		caption.setText(captionText);
		log = (TextView) findViewById(R.id.textView_Log);
		clearLog();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setConnectionView();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_options:
			Intent i = new Intent(Main.this, Preferences.class);
			startActivity(i);
			Toast.makeText(Main.this, R.string.options_tooltip, Toast.LENGTH_LONG).show();
			break;
		case R.id.menu_reconnect:
			connect();
			break;
		}
		return true;
	}

	public void clearLog() {
		log.setText("");
	}

	public void writeLog(String msg) {
		log.setText(log.getText() + msg);
	}

	public void clearSelectedPanel() {
		selectedPanel = null;
	}
	
	public String getSelectedPanel() {
		return selectedPanel; 
	}
	
	public void selectPanel() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		selectedPanel = prefs.getString("autoselectid", "panel_k");
	}

	public void runSimulation(String panelId) {
		myview = new SimulatorView(this, panelId, netClient);
		setContentView(myview);
	}
	
	public void setControlValue(String id, int value) {
		myview.setControlValue(id, value);
	}

	public void connect() {
		if (netClient != null) {
			netClient.close();
			netClient = null;
		}
		setConnectionView();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		String host = prefs.getString("host", "192.168.1.3");
		int port = Integer.parseInt(prefs.getString("port", "4242"));
		netClient = new CPSClientConnection(this, host, port);
		netClient.start();
	}
}